package com.binhthuan.catechist.server.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.binhthuan.catechist.server.ErrorObject;
import com.binhthuan.catechist.server.ResponseObject;
import com.binhthuan.catechist.server.bus.YearBUS;
import com.binhthuan.catechist.server.domain.Year;
import com.binhthuan.catechist.shared.constant.Parameter;

public class YearServlet extends AbstractServlet {

    /**
     * 
     */
    private static final long serialVersionUID = -1549681452606177898L;

    @Override
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        addSchoolYear(request, response);
    }

    @Override
    protected void fetch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter(Parameter.ID) == null) {
            getAllSchoolYears(request, response);
        } else {
            getSchoolYearById(request, response);
        }
    }

    @Override
    protected void remove(HttpServletRequest request, HttpServletResponse response, boolean confirmation) throws ServletException,
            IOException {
        removeSchoolYear(request, response);
    }

    @Override
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        updateSchoolYear(request, response);
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void addSchoolYear(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String description = request.getParameter(Parameter.DESCRIPTION);
        String startDateString = request.getParameter(Parameter.START_DATE);
        String endDateString = request.getParameter(Parameter.END_DATE);

        try {
            java.util.Date startDate = dateFormatter.parse(startDateString);
            java.util.Date endDate = dateFormatter.parse(endDateString);

            if (startDate.compareTo(endDate) >= 0) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.END_DATE, getMessagesFactory().invalidDateRange());
                sendResponse(error.toJson());
                return;
            }

            YearBUS yearBus = new YearBUS();
            Year newSchoolYear = new Year();
            newSchoolYear.setDescription(description.trim());
            newSchoolYear.setStartDate(startDate);
            newSchoolYear.setEndDate(endDate);

            if (yearBus.save(newSchoolYear)) {
                sendResponse(new ResponseObject(newSchoolYear).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void removeSchoolYear(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String yearId = request.getParameter(Parameter.ID);

        try {
            int id = Integer.parseInt(yearId);

            YearBUS yearBus = new YearBUS();
            if (yearBus.checkSchoolYearIsInUsed(id)) {
               ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
               error.addError(Parameter.DESCRIPTION, getMessagesFactory().schoolYearIsInUsed());
               sendResponse(error.toJson());
               return;
            }

            if (yearBus.deleteSchoolYear(id)) {
                sendResponse(new ResponseObject((Object) null).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void updateSchoolYear(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String yearId = request.getParameter(Parameter.ID);
        String description = request.getParameter(Parameter.DESCRIPTION);
        String startDateString = request.getParameter(Parameter.START_DATE);
        String endDateString = request.getParameter(Parameter.END_DATE);

        try {
            int id = Integer.parseInt(yearId);
            java.util.Date startDate = dateFormatter.parse(startDateString);
            java.util.Date endDate = dateFormatter.parse(endDateString);

            if (startDate.compareTo(endDate) >= 0) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.END_DATE, getMessagesFactory().invalidDateRange());
                sendResponse(error.toJson());
                return;
            }

            YearBUS yearBus = new YearBUS();
            Year schoolYear = yearBus.getSchoolYearById(id);
            schoolYear.setDescription(description.trim());
            schoolYear.setStartDate(startDate);
            schoolYear.setEndDate(endDate);

            if (yearBus.save(schoolYear)) {
                sendResponse(new ResponseObject(schoolYear).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void getAllSchoolYears(HttpServletRequest request, HttpServletResponse response) throws IOException {
        YearBUS yearBus = new YearBUS();
        List<Year> years = yearBus.getAllSchoolYears();

        sendResponse(new ResponseObject(years).toJson());
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void getSchoolYearById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter(Parameter.ID);
        try {
            int yearId = Integer.parseInt(id);
            YearBUS yearBus = new YearBUS();
            Year year = yearBus.getSchoolYearById(yearId);
            sendResponse(new ResponseObject(year).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}
